package com.cugmarket.config;

import com.cugmarket.utils.LoginInterceptor;
import com.cugmarket.utils.RefreshTokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
public class MvcConfig implements WebMvcConfigurer {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //order值越大，越后执行
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns(
                        "/shop/**",
                        "/voucher/**",
                        "/shop-type/**",
                        "/user/logout",
                        "/user/sendCode", // 排除发送验证码接口
                        "/user/loginWithCode", // 排除验证码登录接口
                        "/user/loginWithPassword", // 排除密码登录接口
                        "/user/getUserInfo", //获取当前登录用户的信息
                        "/user/comments/{productId}",
                        "/user/productInfo/list",
                        "/user/productInfo/types",
                        "/user/productInfo/id",
                        "/user/productInfo/position",
                        "/user/productInfo/essearch",
                        "/admin/**" // 排除管理员接口
                ).order(1);

        registry.addInterceptor(new RefreshTokenInterceptor(stringRedisTemplate)).addPathPatterns("/**").order(0);
    }

    /**
     * 解决CORS跨域配置
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .exposedHeaders("Authorization")
                .allowCredentials(true)
                .maxAge(3600);  // 可以增加maxAge，允许浏览器缓存CORS预请求的响应
    }
}
